<template>
    <div class="my-dialog">
        <el-dialog v-model="dialogVisible" :title="dialogForm.title" :width="dialogForm.width">
            <el-form :model="form" ref="ruleFormRef" :rules="rules">
                <el-form-item label="举报人" :label-width="formLabelWidth" prop="reportUser">
                    <el-input v-model="form.reportUser" autocomplete="off" placeholder="请输入举报人姓名" />
                </el-form-item>
                <el-form-item label="身份证信息" :label-width="formLabelWidth" prop="reportUserCard">
                    <el-input v-model="form.reportUserCard" autocomplete="off" placeholder="请输入身份证信息" />
                </el-form-item>
                <el-form-item label="被举报单位" :label-width="formLabelWidth" prop="unitName">
                    <el-input v-model="form.unitName" autocomplete="off" placeholder="请输入被举报单位" />
                </el-form-item>
                <el-form-item label="举报所在地" :label-width="formLabelWidth" prop="townId">
                    <el-select style="width: 100%;" v-model="form.townId" filterable placeholder="请选择" clearable
                        @change="onSelect">
                        <el-option v-for="item in Towns" :key="item.areaCode" :label="item.name" :value="item.areaCode">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="详细地址" :label-width="formLabelWidth" prop="address">
                    <el-input v-model="form.address" autocomplete="off" type="textarea" :rows="4"
                        placeholder="请输入详细地址" />
                </el-form-item>
                <el-form-item label="举报接收单位" :label-width="formLabelWidth" prop="acceptUnit">
                    <el-input v-model="form.acceptUnit" :readonly="true" autocomplete="off" placeholder="请输入接收单位" />
                </el-form-item>
                <el-form-item label="举报内容" :label-width="formLabelWidth" prop="reportContent">
                    <el-input v-model="form.reportContent" autocomplete="off" type="textarea" :rows="4"
                        placeholder="请输入举报内容" />
                </el-form-item>
                <el-form-item label="举报照片" :label-width="formLabelWidth" prop="reportImgs">
                    <el-upload :class="{ disabled: uploadDisabled }" v-model:file-list="fileList"
                        :action="`${$baseURL}/manage/upload/uploadReFile`" list-type="picture-card" :headers="{
            'API-User-Token': userInfo.token,
        }" :data="{ 'type': 1 }" :limit="9" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
                        :on-success="handleSuccess" :on-change="handleLimit">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>

                    <el-dialog v-model="dialogVisibleImg">
                        <img w-full :src="dialogImageUrl" alt="Preview Image" />
                    </el-dialog>
                </el-form-item>
                <el-form-item label="举报附件" :label-width="formLabelWidth" prop="reportImgs">
                    <el-upload v-model:file-list="fujianList" :action="`${$baseURL}/manage/upload/uploadReFile`"
                        multiple :headers="{
            'API-User-Token': userInfo.token,
        }" :data="{ 'type': 2 }" :limit="6" :on-success="handleSuccess2" :on-remove="handleRemove2">
                        <el-button type="primary">上传</el-button>
                    </el-upload>

                </el-form-item>
            </el-form>
            <div class="btn-box">
                <el-button @click="resetForm(ruleFormRef)" :loading="loading">取消</el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="loading">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
// @ts-ignore
import { store } from '@/store'
import { getUserInfo } from '@/global/session'

import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { ref, reactive, watch, computed } from 'vue'
import { addApi, getMyTownApi } from '../api/dangerApi'
import type { UploadProps, UploadUserFile, UploadFile, UploadFiles } from 'element-plus'

const $baseURL = import.meta.env.MODE === 'development' ? '/api' : ''
const uploadDisabled = ref(false)

let userInfo = reactive({ token: '' })
userInfo = JSON.parse(getUserInfo() as string)

const dialogVisible = ref<boolean>(false) //弹窗是否出现
const dialogVisibleImg = ref<boolean>(false) //弹窗是否出现
const ruleFormRef = ref<FormInstance>()
const formLabelWidth = '140px'
const dialogForm = {
    width: '50%',
    title: '有奖举报',
}
//监听加载
const loading = computed(() => {
    return store.getters['loading/getLoad']
})
const emit = defineEmits(['onCancel'])

const dialogImageUrl = ref('')
const fileItem = ref('')
const fujianItem = ref('')
const fileList = ref<UploadUserFile[]>([
])
const fujianList = ref<UploadUserFile[]>([
])
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisibleImg.value = true
}
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    let arr = []
    // @ts-ignore
    uploadFiles.map((item) => {
        arr.push(item.response.data.fileIds[0])
    })
    fileItem.value = arr.join(',')
    uploadDisabled.value = false;

}
const handleRemove2: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    let arr = []
    // @ts-ignore
    uploadFiles.map(item => {
        arr.push(item.response.data.fileIds[0])
    })
    fujianItem.value = arr.join(',')

}
const handleSuccess = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
    let arr = []
    // @ts-ignore
    uploadFiles.map((item) => {
        arr.push(item.response.data.fileIds[0])
    })
    fileItem.value = arr.join(',')
};
const handleSuccess2 = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
    let arr = []
    // @ts-ignore
    uploadFiles.map(item => {
        arr.push(item.response.data.fileIds[0])
    })
    fujianItem.value = arr.join(',')
};

const handleLimit = (file, fileList) => {

    if (fileList.length >= 9) {
        uploadDisabled.value = true;
    }
}

interface PropsDialog {
    isShowDialog: boolean //弹窗是否出现
    dialogData?: any
    isBack?: boolean // 详情页调用

}
const props = withDefaults(defineProps<PropsDialog>(), {
    isShowDialog: false,
    isBack: false

})
//获取转移目标人数据及筛选
const Towns: any = ref([])
const TargetUserChange = (val: any) => {

    getMyTownApi().then((res) => {
        if (res.code == 0) {
            Towns.value = res.data
        }
    })
}
TargetUserChange('')

//监控弹窗是否出现
watch(
    () => props.isShowDialog,
    () => {
        ruleFormRef.value?.resetFields()
        fileList.value = []
        fileItem.value = ''
        fujianList.value = []
        fujianItem.value = ''
        dialogVisible.value = !dialogVisible.value
    }
)

const form = reactive({
    reportUser: '',
    reportUserCard: '',
    unitName: '',
    townId: '',
    townName: '',
    address: '',
    acceptUnit: '宁乡应急管理局',
    reportContent: ''
})
const onSelect = (val) => {
    form.townName = Towns.value.filter(item => item.areaCode == val)[0].name
}
const rules = reactive<FormRules>({
    reportUser: [
        {
            required: true,
            message: '请输入举报人',
            trigger: 'change',
        },
    ],
    unitName: [
        {
            required: true,
            message: '请输入被举报单位',
            trigger: 'change',
        },
    ],
    townId: [
        {
            required: true,
            message: '请选择举报问题所在地',
            trigger: 'change',
        },
    ],
    address: [
        {
            required: true,
            message: '请输入详细地址',
            trigger: 'change',
        },
    ],
    reportContent: [
        {
            required: true,
            message: '请输入举报内容',
            trigger: 'change',
        },
    ],
})

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    dialogVisible.value = !dialogVisible.value
}

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            let params = { ...form, reportImgs: fileItem.value, reportFiles: fujianItem.value }

            addApi(params).then((res) => {
                if (res.code == 0) {
                    ElMessage.success('已提交')
                    ruleFormRef.value?.resetFields()
                    dialogVisible.value = !dialogVisible.value
                    setTimeout(() => {
                        //刷新表格
                        store.commit('refresh/setRefresh', !store.getters['refresh/getRefresh'])

                    }, 1000);
                } else {
                    store.commit('loading/setLoad', false)
                }
            })
        } else {
            store.commit('loading/setLoad', false)
        }
    })
}
</script>
<style scoped lang="scss">
.btn-box {
    text-align: right;
}

// .el-upload--picture-card 控制加号部分
.disabled {
    :deep(.el-upload--picture-card) {
        display: none !important;
    }
}
</style>
